#!/usr/bin/env python
#_*_coding:utf-8_*_
'''
 * Created on 2016/10/10 22:13.
 * @author: Chinge_Yang.
'''

import os
import getpass

retry_max = 3
retry_count = 0
user_file = "user.txt"
lock_file = "user_lock.txt"
user_same = 0
user_tmp = ""

if not os.path.exists(lock_file):   #不存在时，则创建
    f = open(lock_file,'w')
    f.close()


while retry_count < retry_max:
    #输入用户名
    user_name = input("Please input your name:")
    #输入的用户名和上次输入的对比
    if user_name == user_tmp:
        #用户一样数加1
        user_same += 1
    else:
        #用户一样数归0
        user_same = 0
    #输入的用户名存为临时变量
    user_tmp = user_name

    #判断用户是否被锁
    lock_check = open(lock_file)
    for line in lock_check:
        line = line.split()
        #用户被锁，打印提示
        if user_name == line[0]:
            exit("User \033[1;31;40m%s\033[0m is locked!" % user_name)
    lock_check.close()

    #查看是否存在于用户数据库
    user_check = open(user_file)
    for l in user_check:
        l = l.split()
        user = l[0]
        passwd = l[1]
        if user_name == user:
            #输入密码
            #user_passwd = input("Please input your password:")
            user_passwd = getpass.getpass("\033[1;33;40mPlease input your password:\033[0m")
            #判断密码是否正确
            if user_passwd == passwd:
                exit("\033[1;32;40mWelcome to you!\033[0m")
            else:
                print("User \033[1;31;40m%s\033[0m password is error!" % user_name)
            #用户存在于数据库，跳出循环
            break
    else:
        print("User \033[1;31;40m%s\033[0m not match in the user file!" % user_name)
    user_check.close()

    if user_same >= 2:
        print("User \033[1;31;40m%s\033[0m name was locked!" % user_name)
        #将用户名写入到锁定文件中
        file = open(lock_file,"a")
        file.write(user_name+"\n")
        file.close()
    retry_count += 1